#include "L0PlugSuitInjected_Stage1.h"
#include <unistd.h>
#include <stdio.h>
#include <dlfcn.h>
#include <limits.h>

void L0PlugSuitInjected_Stage1() {
	CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFSTR("net.infinite-labs.PlugSuit.Support"));
	CFURLRef stage2URL = CFBundleCopyResourceURL(bundle, CFSTR("PlugSuitStage2"), CFSTR("dylib"), NULL);
	CFStringRef stage2Path = CFURLCopyFileSystemPath(stage2URL, kCFURLPOSIXPathStyle);
	
	char fsrep[CFStringGetMaximumSizeOfFileSystemRepresentation(stage2Path)];
	CFStringGetFileSystemRepresentation(stage2Path, fsrep, sizeof(fsrep));
	
#ifdef L0PlugSuitDebug
	fprintf(stderr, "from PlugSuit: [DEBUG] Got %s as file system representation of the dylib in pid %d.\n", fsrep, getpid());
#endif
	
	void* library = dlopen(fsrep, RTLD_NOW | RTLD_GLOBAL);
	if (!library)
		fprintf(stderr, "from PlugSuit: Could not load stage 2 because of a dlopen error. (%s in pid %d)\n", dlerror(), getpid());
	else {
		void (*handle)() = dlsym(library, "L0PlugSuitInjected_Stage2");

		if (!handle)
			fprintf(stderr, "from PlugSuit: Could not find the stage 2 call symbol. (%s in pid %d)\n", dlerror(), getpid());
		else {
#ifdef L0PlugSuitDebug
			fprintf(stderr, "from PlugSuit: [DEBUG] Found handle at %p.\n", handle);
#endif
			handle();
		}
		
		//dlclose(library); // do not risk losing the classes prematurely.
	}
	
	CFRelease(stage2Path);
	CFRelease(stage2URL);
}